package tencent

import (
	"fmt"
	"gitee.com/bobo-rs/creative-framework/enums"
	"gitee.com/bobo-rs/creative-framework/pkg/sms/models"
	tencentErr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	tencentSms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
	"strconv"
	"time"
)

// commonErrorHandler 统一处理响应资源错误信息
func (h *Handler) commonErrorHandler(err error) error {
	// 处理异常
	if _, ok := err.(*tencentErr.TencentCloudSDKError); ok {
		return fmt.Errorf(`tencent an API  has returned: %s`, err)
	}
	// 非SDK异常，直接失败。实际代码中可以加入其他的处理。
	if err != nil {
		return fmt.Errorf(`tencent api request failed %w`, err)
	}
	return nil
}

// pullSmsSendStatusSetResponse 拉取短信发送状态响应集合
func (h *Handler) pullSmsSendStatusSetResponse(statusSet []*tencentSms.PullSmsSendStatus) []*models.PullSendResultItem {
	if len(statusSet) == 0 {
		return nil
	}
	// 处理集合
	results := make([]*models.PullSendResultItem, 0)
	for _, r := range statusSet {
		results = append(results, &models.PullSendResultItem{
			CommonSmsResultItem: models.CommonSmsResultItem{
				Mobile:   *r.SubscriberNumber,
				SerialNo: *r.SerialNo,
			},
			SendState:       *r.ReportStatus,
			Description:     *r.Description,
			UserReceiveTime: int(*r.UserReceiveTime),
		})
	}
	return results
}

// sendStatusSetResponse 短信发送状态集合响应处理
func (h *Handler) sendStatusSetResponse(statusSet []*tencentSms.SendStatus) []models.SendSmsResultItem {
	if len(statusSet) == 0 {
		return nil
	}
	// 发送结果
	results := make([]models.SendSmsResultItem, 0)
	for _, result := range statusSet {
		results = append(results, models.SendSmsResultItem{
			CommonSmsResultItem: models.CommonSmsResultItem{
				SerialNo: *result.SerialNo,
				Mobile:   *result.PhoneNumber,
			},
			Code:    *result.Code,
			Message: *result.Message,
		})
	}
	return results
}

// describeTemplateStatusSetResponse 短信模板状态查询
func (h *Handler) describeTemplateStatusSetResponse(statusSet []*tencentSms.DescribeTemplateListStatus) []*models.SmsListResultItem {
	if len(statusSet) == 0 {
		return nil
	}
	// 迭代结果
	results := make([]*models.SmsListResultItem, 0)
	for _, result := range statusSet {
		t := time.Unix(int64(*result.CreateTime), 0)
		var status uint
		switch *result.StatusCode {
		case 0:
			status = 1 // 审核通过
		case -1:
			status = 2 // 审核失败
		}
		results = append(results, &models.SmsListResultItem{
			TemplateId:   strconv.FormatUint(*result.TemplateId, 10),
			SmsTypeText:  enums.TencentSmsInternational(*result.International).Fmt(),
			StatusText:   enums.TencentSmsStatusCode(*result.StatusCode).Fmt(),
			Status:       status,
			Reply:        *result.ReviewReply,
			TemplateName: *result.TemplateName,
			Content:      *result.TemplateContent,
			CreateAt:     t.Format(time.DateTime),
		})
	}
	return results
}
